package com.atzxh.guigu.juc.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *  演示可重入锁：synchronized（隐式） 和  Lock（显式）都是可重入锁（递归锁）
 */
public class SyncLockDemo {
    public static void main(String[] args) {
        // synchronized
//        Object o = new Object();
//        new Thread(()->{
//            System.out.println(Thread.currentThread().getName() + "：外层");
//
//            synchronized (o) {
//                System.out.println(Thread.currentThread().getName() + "：中层");
//
//                synchronized (o) {
//                    System.out.println(Thread.currentThread().getName() + "：内层");
//                }
//            }
//        },"aa").start();

        // Lock
        Lock lock = new ReentrantLock();
        new Thread(()->{
            try {
                lock.lock();
                System.out.println(Thread.currentThread().getName() + "：外层");

                try {
                    lock.lock();
                    System.out.println(Thread.currentThread().getName() + "：内层");
                } finally {
                    lock.unlock();
                }
            } finally {
                lock.unlock();
            }
        },"aa").start();
    }

    /**
     *  递归调用    StackOverflow
     */
    public synchronized void add() {
        add();
    }
}
